﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZeroMQ;

namespace ZmqServer
{
    class Program
    {
        private static int port = 8889;
        static void Main(string[] args)
        {
            port = int.Parse(args[0]);
            Task.Factory.StartNew(Server, null, TaskCreationOptions.LongRunning);
            Console.ReadLine();
        }

        private static void Server(object state)
        {
            var buffer = new byte[1024 * 1024];
            using (var ctx = ZmqContext.Create())
            {
                try
                {
                    using (var socket = ctx.CreateSocket(SocketType.REP))
                    {
                        var bind = string.Format("tcp://*:{0}", port);
                        socket.Bind(bind);
                        while (true)
                        {
                            var lpiLen = socket.Receive(buffer);

                            var lpi = Deserialize(buffer, lpiLen);

                            Console.WriteLine("receive {0} age: {1}, time: {2}", lpi.Id, lpi.Age, lpi.CaptureTime);
                            socket.Send(lpi.Id, Encoding.Unicode);
                            Console.WriteLine("\t echo " + lpi.Id);
                        }

                    }
                }
                catch (ZmqSocketException ex)
                {
                    Console.WriteLine(ex.Message);
                    File.WriteAllText("log.txt", ex.ToString());
                }

            }
        }

        private static Messages.Lpi Deserialize(byte[] buffer, int lpiLen)
        {
            using (var s = new MemoryStream(buffer, 0, lpiLen))
            {
                return ProtoBuf.Serializer.Deserialize<Messages.Lpi>(s);
            }
        }
    }
}
